package com.kaguya.vams.security.handler;

import cn.hutool.json.JSONUtil;
import com.kaguya.vams.common.constant.HttpStatus;
import com.kaguya.vams.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败
 * @author : kaguya
 * @date : 2:24 2021/8/1
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        log.info("认证失败入口点 - ");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //设置响应状态码 未认证 401
        //httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.getCode());
        ServletOutputStream sos = httpServletResponse.getOutputStream();

        //返回失败信息
        Result result = Result.msg(HttpStatus.UNAUTHORIZED.getCode(),"请先登录");

        //转成json并写入
        sos.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        sos.flush();
        sos.close();
    }
}
